package com.example.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.Dto.UserDto;
import com.example.domain.User;
import com.example.mapper.UserMapper;
import com.example.service.IUserService;
import com.example.service.ex.InsertException;
import com.example.service.ex.YzmException;
import com.example.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 用户业务
 */
@Service
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Long save(UserDto userDto,String code) {
        //获取手机号
        String phone = userDto.getPhone();
        //获取验证码
        String code1 = userDto.getCode();
        if (code1==null&&!code.equals(code1)){
            throw new YzmException("验证码错误");
        }
        //创建条件构造器查询手机号是否以存在
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<User>();
        lambdaQueryWrapper.eq(phone!=null,User::getPhone,phone);
        User user = userMapper.selectOne(lambdaQueryWrapper);
        //判断用户是否为空
        if(user==null){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            int insert = userMapper.insert(user);
            if (insert<=0){
                throw new InsertException("添加数据时产生未知的异常");
            }
        }
        //获取用户id的返回
        return user.getId();
    }

    @Override
    public User getById(Long userId) {
        User user = userMapper.selectById(userId);
        return user;
    }

}
